import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Calendar;


public class SSHFormat {
	private static final String PUBFILE = "key.pub";
	private static final String PEMFILE = "key.pem";

    private static BigInteger readBigIntFromFile(String fileName) throws FileNotFoundException,IOException {
    	File inFile = new File(fileName);
    	FileInputStream fis = new FileInputStream(inFile);
        byte[] b = new byte[(int)inFile.length()];
        fis.read(b);
        String s = new String(b);
        BigInteger bigInt = new BigInteger(SSHBase64.decode(s));
        fis.close();
        return bigInt;
    }
    private static void renderPub(BigInteger e,BigInteger n,String pubFile) throws FileNotFoundException,IOException{
    	String begin = "---- BEGIN SSH2 PUBLIC KEY ----\r\n";
    	String end   = "---- END SSH2 PUBLIC KEY ----\r\n";
    	String subject = "Subject: LuatAndTri\r\n";
    	Calendar dateTime = Calendar.getInstance();
    	String comment = "Comment: RSA Algorithm, created by LuatAndTri " + dateTime.getTime() + "\r\n";
    
    	if (comment.length() > SSHBase64.splitLinesAt)
    		comment = comment.substring(0,SSHBase64.splitLinesAt) + "\\\r\n" + 
    				comment.substring(SSHBase64.splitLinesAt,comment.length());
    	String base64E = SSHBase64.encode(e.toString());
    	String base64N = SSHBase64.encode(n.toString());
    	
    	FileWriter fw = new FileWriter(new File(pubFile));
    	fw.write(begin);
    	fw.write(subject);
    	fw.write(comment);
    	fw.write(SSHBase64.splitLines(base64E+base64N));
    	fw.write(end);
    	
    	fw.close();
    }
    
    private static void renderPem(BigInteger d,BigInteger n,String pubFile) throws FileNotFoundException,IOException{
    	String begin = "-----BEGIN RSA PRIVATE KEY-----\r\n";
    	String end   = "-----END RSA PUBLIC KEY-----\r\n";
 
    	String base64D = SSHBase64.encode(d.toString());
    	String base64N = SSHBase64.encode(n.toString());
    	
    	FileWriter fw = new FileWriter(new File(pubFile));
    	fw.write(begin);
    	fw.write(SSHBase64.splitLines(base64D+base64N));
    	fw.write(end);
    	
    	fw.close();
    }
    public static void main(String[] args) {
        String eFile,dFile,pFile,qFile;
        try {
        	eFile = args[0];
        	dFile = args[1];
        	pFile = args[2];
        	qFile = args[3];
        	BigInteger e  = readBigIntFromFile(eFile);
        	BigInteger d  = readBigIntFromFile(dFile);
        	BigInteger p  = readBigIntFromFile(pFile);
        	BigInteger q  = readBigIntFromFile(qFile);
        	BigInteger n = p.multiply(q);
        	
        	renderPub(e,n,PUBFILE);
        	renderPem(d,n,PEMFILE);
        }
        catch (IndexOutOfBoundsException ex) {
            System.err.println("Not enough files. You must pass 4 files containing these numbers : e,d,p,q.");
            System.exit(1);
            
        }
        catch (FileNotFoundException fnfe) {
            System.err.println("File(s) cannot be found.");
            System.exit(1);
        }
        catch (IOException e) {
            System.err.println("IO Exception.");
            System.exit(1);
        }
    }
}
class SSHBase64 {
	public static final int splitLinesAt = 72;
	private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/";
	private static byte[] zeroPad(int length, byte[] bytes) {
        byte[] padded = new byte[length]; // initialized to zero by JVM
        System.arraycopy(bytes, 0, padded, 0, bytes.length);
        return padded;
    }
    public static String splitLines(String string) {
        String lines = "";
        for (int i = 0; i < string.length(); i += splitLinesAt) {
            lines += string.substring(i, Math.min(string.length(), i + splitLinesAt));
            lines += "\r\n";
        }
        return lines;
    }
	public static String encode(String string) {
		 
        String encoded = "";
        byte[] stringArray;
        try {
            stringArray = string.getBytes("UTF-8");  // use appropriate encoding string!
        } catch (Exception ignored) {
            stringArray = string.getBytes();  // use locale default rather than croak
        }
        // determine how many padding bytes to add to the output
        int paddingCount = (3 - (stringArray.length % 3)) % 3;
        // add any necessary padding to the input
        stringArray = zeroPad(stringArray.length + paddingCount, stringArray);
        // process 3 bytes at a time, churning out 4 output bytes
        // worry about CRLF insertions later
        for (int i = 0; i < stringArray.length; i += 3) {
            int j = ((stringArray[i] & 0xff) << 16) +
                ((stringArray[i + 1] & 0xff) << 8) + 
                (stringArray[i + 2] & 0xff);
            encoded = encoded + base64code.charAt((j >> 18) & 0x3f) +
                base64code.charAt((j >> 12) & 0x3f) +
                base64code.charAt((j >> 6) & 0x3f) +
                base64code.charAt(j & 0x3f);
        }
        return encoded + "==".substring(0, paddingCount);
        
    }

	public static String decode(String string) {
		int length = string.length();
		int paddingCount;
		if(string.charAt(length-2) == '=')
			paddingCount = 2;
		else if (string.charAt(length-1) == '=')
			paddingCount = 1;
		else paddingCount = 0;
		
		string = string.substring(0,string.length()-paddingCount);
		byte[] decodedArray = new byte[string.length()*3/4];
		int j;
		int byteIndex = 0;
		for (int i = 0 ; i < string.length() ; i += 4) {		
			j = base64code.indexOf(string.charAt(i));
			j <<= 6;
			j |= base64code.indexOf(string.charAt(i+1));
			j <<= 6;
			j |= base64code.indexOf(string.charAt(i+2));
			j <<= 6;
			j |= base64code.indexOf(string.charAt(i+3));

			decodedArray[byteIndex+2] = (byte)(j);
			j >>= 8;
			decodedArray[byteIndex+1] = (byte)(j);
			j >>= 8;
			decodedArray[byteIndex] = (byte)(j);
			j >>= 8;
			byteIndex += 3;
		}
		byte[] returnArr = new byte[decodedArray.length - paddingCount];
		System.arraycopy(decodedArray,0,returnArr,0,decodedArray.length - paddingCount);
        return new String(returnArr);
    }
}
// javac src/SSHFormat.java
// java -cp bin SSHFormat e.numb d.numb p.numb q.numb
